package com.example.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.library.entity.Borrowing;
import com.example.library.entity.User;
import com.example.library.mapper.BorrowingMapper;
import com.example.library.service.IBorrowingService;
import com.example.library.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sx
 * @since 2024-12-17
 */
@RestController
public class BorrowingController {
    @Autowired
    private IBorrowingService borrowingService;

    @Autowired
    private BorrowingMapper borrowingMapper;

    @Autowired
    private IUserService userService;

    //查阅所有的借阅记录
    @GetMapping("/borrowing/list")
    public List<Borrowing> getBorrowings(){
        return borrowingMapper.select();
    }

    //根据用户ID查询借阅记录
    @GetMapping("/borrowing/search/userId/{UserID}")
    public ResponseEntity<List<Borrowing>> getBorrowingsByUserID(@PathVariable Long UserID){
        List<Borrowing> borrowings = borrowingService.lambdaQuery()
                .eq(Borrowing::getUserid,UserID)
                .list();
        return ResponseEntity.ok(borrowings);
    }

    // 根据书籍ID查询借阅记录
    @GetMapping("/borrowing/search/bookId/{BookID}")
    public ResponseEntity<List<Borrowing>> getBorrowingsByBookId(@PathVariable Long BookID) {
        List<Borrowing> borrowings = borrowingService.lambdaQuery()
                .eq(Borrowing::getBookid, BookID)
                .list();
        return ResponseEntity.ok(borrowings);  // 返回200 OK 和书籍的借阅记录
    }

    // 根据借阅日期范围查询借阅记录
    @GetMapping("/borrowing/date")
    public ResponseEntity<List<Borrowing>> getBorrowingsByDateRange(@RequestParam String startDate, @RequestParam String endDate) {
        List<Borrowing> borrowings = borrowingService.lambdaQuery()
                .ge(Borrowing::getBorrowdate, startDate)
                .le(Borrowing::getReturndate, endDate)
                .list();
        return ResponseEntity.ok(borrowings);  // 返回200 OK 和符合日期范围的借阅记录
    }

//    // 根据借阅记录ID查询单个借阅记录
//    @GetMapping("/borrowing/{id}")
//    public ResponseEntity<Borrowing> getBorrowingById(@PathVariable Long id) {
//        Borrowing borrowing = borrowingService.getById(id);
//        if (borrowing != null) {
//            return ResponseEntity.ok(borrowing);  // 返回200 OK 和借阅记录
//        } else {
//            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();  // 返回404 Not Found
//        }
//    }

    /**
     * 查询当前登录用户的借阅记录
     */
    @GetMapping("/myBorrowings")
    public ResponseEntity<List<Borrowing>> getMyBorrowings() {
        try {
            // 从 Spring Security 获取当前登录用户 ID
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
            }

            Object principal = authentication.getPrincipal();
            String name;

            if (principal instanceof UserDetails) {
                name = ((UserDetails) principal).getUsername();
            } else {
                name = principal.toString();
            }

            // 根据用户名查找用户 ID（假设 User 表中有唯一的 username 字段）
            Integer userId = getUserIdByUsername(name);

            // 根据用户 ID 查询借阅记录
            List<Borrowing> borrowings = borrowingService.lambdaQuery()
                    .eq(Borrowing::getUserid, userId)
                    .list();

            return ResponseEntity.ok(borrowings);

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    private Integer getUserIdByUsername(String name) {
        // 假设 IUserService 提供一个方法来通过用户名获取用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("name", name));
        return user != null ? user.getId() : null;
    }


}
